#!/usr/bin/env python
# -*- coding: UTF-8; indent-tabs-mode:nil; tab-width:4 -*-

# This file is part of DITA DTD Generator.
#
# DITA DTD Generator is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# DITA DTD Generator is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with DITA DTD Generator.  If not, see <http://www.gnu.org/licenses/>.

"""Command line interface to DITA DTD Generator."""

import sys
import os
import re
#import time
#import datetime
#import tempfile
#import tarfile
import ditagen.dtdgen
#import ditagen.dita.v1_2
from ditagen.dita.v1_2 import *
from ditagen.dita.v1_1 import *
import ditagen.generator
import getopt

DOMAIN_MAP = {
    1.1: {
        "ui": ditagen.dita.v1_1.UiDomain,
        "hi": ditagen.dita.v1_1.HiDomain,
        "pr": ditagen.dita.v1_1.PrDomain,
        "sw": ditagen.dita.v1_1.SwDomain,
        "ut": ditagen.dita.v1_1.UtDomain,
        "indexing": ditagen.dita.v1_1.IndexingDomain,
        "mapgroup": ditagen.dita.v1_1.MapGroupDomain,
        "abbreviated": ditagen.dita.v1_1.AbbreviatedFormDomain,
        "xnal": ditagen.dita.v1_1.XNALDomain,
        },
    1.2: {
        "ui": ditagen.dita.v1_2.UiDomain,
        "hi": ditagen.dita.v1_2.HiDomain,
        "pr": ditagen.dita.v1_2.PrDomain,
        "sw": ditagen.dita.v1_2.SwDomain,
        "ut": ditagen.dita.v1_2.UtDomain,
        "indexing": ditagen.dita.v1_2.IndexingDomain,
        "learning": ditagen.dita.v1_2.LearningDomain,
        "learningmeta": ditagen.dita.v1_2.LearningMetaDomain,
        "learningmap": ditagen.dita.v1_2.LearningMapDomain,
        "mitask": ditagen.dita.v1_2.MachineIndustryTaskDomain,
        "hazardstatement": ditagen.dita.v1_2.HazardStatementDomain,
        "mapgroup": ditagen.dita.v1_2.MapGroupDomain,
        "abbreviated": ditagen.dita.v1_2.AbbreviatedFormDomain,
        "xnal": ditagen.dita.v1_2.XNALDomain,
        "delay": ditagen.dita.v1_2.UserDelayedResolutionDomain,
        "classify": ditagen.dita.v1_2.ClassifyDomain,
        "taskbody": ditagen.dita.v1_2.MachineIndustryTaskbodyConstraints,
        "strictTaskbody": ditagen.dita.v1_2.StrictTaskbodyConstraints
        }
    }
TOPIC_MAP = {
    1.1: {
        "concept": ditagen.dita.v1_1.ConceptType,
        "reference": ditagen.dita.v1_1.ReferenceType,
        "task": ditagen.dita.v1_1.TaskType,
        "topic": ditagen.dita.v1_1.TopicType,
        "map": ditagen.dita.v1_1.MapType,
        "bookmap": ditagen.dita.v1_1.BookMapType,
        },
    1.2: {
        "concept": ditagen.dita.v1_2.ConceptType,
        "reference": ditagen.dita.v1_2.ReferenceType,
        "task": ditagen.dita.v1_2.TaskType,
        "topic": ditagen.dita.v1_2.TopicType,
        "machineTask": ditagen.dita.v1_2.MachineryTaskType,
        "map": ditagen.dita.v1_2.MapType,
        "bookmap": ditagen.dita.v1_2.BookMapType,
        "classifyMap": ditagen.dita.v1_2.ClassificationMapType,
        "subjectScheme": ditagen.dita.v1_2.SubjectSchemeMapType,
        "learningAssessment": ditagen.dita.v1_2.LearningAssessmentType,
        "learningBookmap": ditagen.dita.v1_2.LearningBookMapType,
        "learningContent": ditagen.dita.v1_2.LearningContentType,
        "learningMap": ditagen.dita.v1_2.LearningMapType,
        "learningOverview": ditagen.dita.v1_2.LearningOverviewType,
        "learningPlan": ditagen.dita.v1_2.LearningPlanType,
        "learningSummary": ditagen.dita.v1_2.LearningSummaryType
        }
    }

def main():
    """Main method."""
    __type = None
    __root = None
    __owner = None
    __nested = None
    __remove = {}
    __global_atts = None
    __format = None
    __domains = []
    __types = []
    __version = 1.1
    __plugin_name = None
    __stylesheet = None
    
    __dms = []    
    
    # read arguments
    try:
        opts, args = getopt.getopt(sys.argv[1:],
                                   "hd:o:f:v:r:s:p:n:",
                                   ["help", "domain=", "owner=", "format=",
                                    "version=", "root=", "stylesheet=",
                                    "plugin-name=", "nested="])
    except getopt.GetoptError:
        usage()
        sys.exit(2)
    if len(args) == 0:
        usage()
        sys.exit(2)
    for opt, arg in opts:
        if opt in ("-h", "--help"):
            usage() 
            sys.exit()
        elif opt in ("-d", "--domain"):
            __dms.extend(arg.split(":"))
        elif opt in ("-f", "--format"):
            if not arg in ("dtd", "mod", "ent", "zip", "plugin"):
                raise ValueError()
            else:
                __format = arg
        elif opt in ("-o", "--owner"):
            __owner = arg
        elif opt in ("-r", "--root"):
            __root = arg
        elif opt in ("-n", "--nested"):
            __nested = arg == "true"
        elif opt in ("-v", "--version"):
            __version = float(arg)
            if not __version in (1.1, 1.2):
                raise ValueError()
        elif opt in ("-p", "--plugin-name"):
            __plugin_name = arg
        elif opt in ("-s", "--stylesheet"):
            __stylesheet = arg
    for arg in args:
        if arg in TOPIC_MAP[__version]:
            __type = TOPIC_MAP[__version][arg]()
    if __type is None:
        usage()
        sys.exit(2)
    for __d in __dms:
        if __d in DOMAIN_MAP[__version]:
            __domains.append(DOMAIN_MAP[__version][__d]())
    
    #__nested = u"nested" in __form
    #__remove = dict([(n, True) for n in __form.getlist("remove")])
    #__global_atts = None#__form.getfirst(u"attribute")
    
    if __root is not None:
        if __version == 1.2:
            __st = ditagen.dita.v1_2.SpecializationType
        else:
            __st = ditagen.dita.v1_1.SpecializationType
        __type = __st(__root, __root, __type, __owner, __root)
    
    # run generator
    if __format == u"plugin":
        __dita_gen = ditagen.generator.PluginGenerator()
        __dita_gen.set_output(sys.stdout)
        __dita_gen.set_topic_type(__type)
        __dita_gen.set_domains(__domains)
        #__dita_gen.set_root(__root)
        #__dita_gen.set_owner(__owner)
        __dita_gen.set_nested(__nested)
        __dita_gen.set_version(__version)
        if __stylesheet:
            __dita_gen.set_stylesheet(__stylesheet)
        __dita_gen.set_plugin_name(__plugin_name)
        
        __file_name = __dita_gen.get_file_name(__type, __root, "zip")
        __dita_gen.generate_plugin()
    else:
        __dita_gen = ditagen.generator.DitaGenerator()
        __dita_gen.set_output(sys.stdout)
        __dita_gen.set_topic_type(__type)
        __dita_gen.set_domains(__domains)
        #__dita_gen.set_root(__root)
        #__dita_gen.set_owner(__owner)
        __dita_gen.set_nested(__nested)
        __dita_gen.set_version(__version)
        
        if __format == u"dtd":
            #__file_name = __dita_gen.get_file_name(__type, __root, __format)
            __dita_gen.generate_dtd()
        elif __format == u"mod":
            #__file_name = __dita_gen.get_file_name(__type, __root, __format)
            __dita_gen.generate_mod()
        elif __format == u"ent":
            #__file_name = __dita_gen.get_file_name(__type, __root, __format)
            __dita_gen.generate_ent()
        elif __format == u"zip":
            #__file_name = __dita_gen.get_file_name(__type, __root, "zip")
            __dita_gen.generate_zip(sys.stdout)
        #elif __format == u"tgz":
        #    __file_name = __dita_gen.get_file_name(__type, __root, "tar.gz")
        #    __dita_gen.generate_zip(sys.stdout, __type, __domains, __root, __owner, __nested, __remove, __global_atts)
        #elif __format == u"xzip":
        #    __file_name = __dita_gen.get_file_name(__type, __root, "zip")
        #    zip_dita_gen = ditagen.generator.ZipGenerator(sys.stdout)
        #    zip_dita_gen.generate_zip(sys.stdout, __type, __domains, __root, __owner, __nested)

def usage():
    """Usage."""
    print """Usage: cli.py [OPTIONS]... TOPIC
DITA DTD Generator commandline tool.

Options:
  -v, --version      DITA version, defaults to 1.1.
  -h, --help         This help.
  -d, --domain       Add domain, multiple domains colon (':') separated
  -f, --format       Output format, one of dtd, mod, ent, zip, plugin
  -o, --owner        Owner in FPI.
  -r, --root         Root name.
  -p, --plugin-name  Plugin name.
  -s, --stylesheet   Stylesheet stump base.

Examples:
  Generate DITA 1.2 Task DTD file without domains or topic nesting
    cli.py -v 1.2 -f dtd task
  Generate DITA 1.1 Reference specialization plugin for DITA-OT
    cli.py -d ui:pr -o EXAMPLE.COM -r exampleref -f plugin -s xhtml reference"""

if __name__ == "__main__":
    main()
